﻿#include "tcpclient.h"
#include "ui_tcpclient.h"
#include<QTcpSocket>
#include<QHostAddress>
#include<QFile>
#include<QFileInfo>
#include<QFileDialog>
#include<QMessageBox>
#include<QDebug>

TcpClient::TcpClient(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TcpClient)
{
    ui->setupUi(this);

    this->setWindowTitle("Client:8888");
    this->setFixedSize(561,445);
    connect(ui->lineEdit,&QLineEdit::returnPressed,
            ui->pushButton,&QAbstractButton::click,Qt::UniqueConnection);

    udpSocket = new QUdpSocket(this);
    udpSocket->bind(8888);
    connect(udpSocket,&QUdpSocket::readyRead,this,&TcpClient::dealrecvMsg);

    tcpSocket = new QTcpSocket(this);
    connectServer();
    connect(tcpSocket,&QTcpSocket::disconnected,this,&TcpClient::dealDisconnect);
}

TcpClient::~TcpClient()
{
    delete ui;
}


/*************************************************
Description:    处理接收的数据UDP
return:         void
Called By:
Auther:         林锦涛
Time:           2021-1-31 14:31:48
*************************************************/
void TcpClient::dealrecvMsg()
{
    char buf[1024] = {0};
    quint16 port;
    QHostAddress cliAddr;

    //读取服务器信息
    qint64 len = udpSocket->readDatagram(buf,sizeof(buf),&cliAddr,&port);

    if(len>0)
    {
        //格式化{193.68.2.2:8888}aaaa
        QString str = QString("[%1: %2] %3")
                .arg(cliAddr.toString())
                .arg(port)
                .arg(buf);

        ui->textEdit->append(str);
    }
}

/*************************************************
  Description:    发送按钮函数
  return:         void
  Called By:
  Auther:         林锦涛
  Time:           2021-1-31 14:31:48
*************************************************/
void TcpClient::on_pushButton_clicked()
{
    //先获取对方的IP和端口
    QString ip= "127.0.0.1";
    qint16 port = 9999;

    QString str =ui->lineEdit->text();
    ui->lineEdit->clear();
    //string 转字节数组 直接.toutf-8
    udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port);

    //tcp点击发送文件
    if (fileName != NULL && fileSize != 0)
    {
        sendSize = 0;
        qint64 len = 0;
        do
        {
            char buf[1024*4];
            len = 0;
            len = file.read(buf,sizeof(buf));
            tcpSocket->write(buf,len);
            sendSize += len;
            //qDebug()<<sendSize<<"  "<<"83";

        }while(len>0);

        if(fileSize == sendSize)
        {
            file.close();
            ui->labelclient->setText(QStringLiteral("文件发送成功!"));
        }
        else
        {
            qDebug()<<QStringLiteral("文件发送失败!")<<"98";
        }

    }

}

/*************************************************
  Description:    tcp连接服务器函数
  return:         void
  Called By:
  Auther:         林锦涛
  Time:           2021-1-31 14:31:48
*************************************************/
void  TcpClient::connectServer()
{
    tcpSocket->connectToHost("127.0.0.1",9999);
    if(tcpSocket->waitForConnected(30000))
    {
        ui->labelclient->setText(QStringLiteral("连接成功!!"));
        ui->btnSelect->setEnabled(true);
        ui->pushButton->setEnabled(true);
    }
    else
    {
        qDebug()<<QStringLiteral("连接失败")<<"121";
    }
}

/*************************************************
  Description:    选择文件函数
  return:         void
  Called By:
  Auther:         林锦涛
  Time:           2021-1-31 14:31:48
*************************************************/
void TcpClient::on_btnSelect_clicked()
{
    QString path = QFileDialog::getOpenFileName(this,"open","../");
    if (!path.isEmpty())
    {
        //qDebug()<<QStringLiteral("文件打开成功! 77");
        fileName.clear();
        fileSize = 0;

        QFileInfo info(path);
        fileName = info.fileName();
        fileSize = info.size();

        file.setFileName(path);
        bool isok = file.open(QIODevice::ReadOnly);
        if (isok)
        {
            //qDebug()<<QStringLiteral("只读打开文件成功! 90");

            QString str = QString("%1 : %2").arg(fileName).arg(fileSize);
            ui->lineEdit->setText(str);
            ui->labelclient->setText(QStringLiteral("文件打开成功!!"));

        }
        else
        {
            qDebug()<<QStringLiteral("只读打开文件失败!  94");
        }
    }
    else
    {
        qDebug()<<QStringLiteral("对话框打开文件失败!  99");
    }

}

/*************************************************
  Description:    tcp断开连接处理
  return:         void
  Called By:
  Auther:         林锦涛
  Time:           2021-1-31 14:31:48
*************************************************/
void TcpClient::dealDisconnect()
{
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    ui->btnSelect->setEnabled(false);
    ui->pushButton->setEnabled(false);
    ui->labelclient->setText(QStringLiteral("断开连接!!!"));
}

/*************************************************
  Description:    重写关闭函数
  return:         void
  Called By:
  Auther:         林锦涛
  Time:           2021-1-31 14:31:48
*************************************************/
void TcpClient::closeEvent(QCloseEvent *e)
{
    if(QMessageBox::question(this,
                             "Quit",
                             "Are you sure to close?",
                             QMessageBox::Yes,QMessageBox::No)
            == QMessageBox::Yes)
    {
        e->accept();
        tcpSocket->close();
    }
    else
    {
        e->ignore();
    }
}
